package com.allenlee.mvphelper.util;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.allenlee.mvphelper.R;

/**
 * @author : lifei
 * 创建时间： 19-11-27
 * 更改时间： 19-11-27
 * Email : allen.lee723@qq.com
 * @version :
 * Description：
 */
public class ToastHelper {
    private static Toast mToast;

    private static Handler mUIHandler = new Handler(Looper.getMainLooper());

    public static void showToast(Context context, int resId) {
        showToast(context, context.getString(resId));
    }

    public static void showToast(Context context, String text) {
        showToast(context, text, Toast.LENGTH_SHORT);
    }

    public static void showLongToast(Context context, int resId) {
        showLongToast(context, context.getString(resId));
    }

    public static void showLongToast(Context context, String text) {
        showToast(context, text, Toast.LENGTH_LONG);
    }

    // 显示消息
    public static void showToast(Context context, String msg, int duration) {

        mUIHandler.post(() -> {
            if (mToast == null) {
                View toastView = LayoutInflater.from(context).inflate(R.layout.toast, null);
                TextView messageTv = toastView.findViewById(R.id.message_tv);
                messageTv.setText(msg);
                mToast = new Toast(context);
                mToast.setDuration(duration);
                mToast.setView(toastView);
            } else {
                ((TextView) ((LinearLayout) mToast.getView()).getChildAt(0)).setText(msg);
            }
            mToast.show();
        });
    }
}
